<template>
    <div>
        <div class="box">
            <div class="left_box">
                <el-button type="primary" @click="btntop">添加顶级知识体系</el-button><el-button type="primary"
                    @click="btnchlidren" :disabled="selectedItem">添加子知识体系</el-button>
                <el-tree ref="treeRef" style="max-width: 300px" :data="data" :props="defaultProps" node-key="id"
                    :expand-on-click-node="false" @node-click="handleNodeClick" />
            </div>
            <div class="right_box">
                <el-form ref="ruleFormRef" :rules="rules" label-width="auto" :model="datatop" style="max-width: 800px">
                    <el-form-item v-if="flage" label="上级菜单" prop="region">
                        <el-tree-select v-model="datatop.id" :data="lants" :props="defaultProps" check-strictly
                            default-expand-all placeholder="请选择上级知识体系" value-key="id" />
                    </el-form-item>
                    <el-form-item label="知识体系名称" prop="name">
                        <el-input v-model="datatop.name" />
                    </el-form-item>
                    <el-form-item label="知识体系编号" prop="code">
                        <el-input v-model="datatop.code" />
                    </el-form-item>
                    <el-form-item label="显示排序" prop="sort">
                        <el-input-number v-model="datatop.sort" :min="0" controls-position="right" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="confirm(ruleFormRef)">确定</el-button>
                        <el-button type="primary" @click="delect(datatop.id)">删除</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { remove, inquiry, editor } from '@/api/knowledgeSystem/system'
import { defaultProps, handleTree } from '@/utils/tree'
import { FormInstance, FormRules, ElMessageBox, ElMessage } from 'element-plus'
import { error } from 'console';
interface RuleForm {
    id?: String,
    name: String,
    code: String,
    pid: Number,
    remark?: string,
    sort: Number,
    hasChildren?: boolean
    children?: RuleForm[]
}
const lists = () => {
    return {
        name: "",
        code: "",
        pid: 0,
        sort: 0
    }
}
const datatop = reactive<RuleForm>(lists())
//表单效验
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入编号', trigger: 'blur' },
    ],
})

// 下拉框是否显示
const flage = ref(false)
const selectedItem = ref(true)
interface Tree {
    label: string
    children?: Tree[]
}
const lants = ref([])
const barID = ref()
const handleNodeClick = (data: Tree) => {
    console.log(data, 'handleNodeClick')
    selectedItem.value = false
    flage.value = false
    datatop.name = data.name
    datatop.code = data.code
    datatop.id = data.id
    datatop.sort = data.sort
    barID.value = data.id
    // 假设当前内容的id为contentId
    const contentId = datatop.id;

    // 查找当前内容在数组中的位置顺序
    // const contentIndex = datatop.findIndex(item => item.id === contentId);
    // console.log('当前内容所在位置的顺序：', contentIndex);
}
const data = ref<Tree[]>([
])
const arr = async () => {
    let list = await inquiry()
    console.log(list, 'list');
    data.value = handleTree(list)
}
arr()
const clearForm = () => {
    const emptyData = lists(); // 获取一个新的空数据对象
    Object.assign(datatop, emptyData); // 将空数据对象的属性复制到 datatop中
};
//点击添加子元素按钮
const btnchlidren = () => {
    flage.value = true
    clearForm()
    lants.value = data.value
}
//点击添加父元素按钮
const btntop = () => {
  flage.value = false;
  clearForm();
  datatop.id = null
}
const ruleFormRef = ref<FormInstance>()
//点击确定按钮实现添加或者修改
const confirm = async () => {
    await ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log(data.value, 'data')
            const res = data.value.filter((item) => item.name === datatop.name)
            if (!res.length || datatop.id) {
                console.log(flage.value);
                if (flage.value) {
                    datatop.pid = datatop.id
                }
                editor(datatop).then(result => {
                    console.log(datatop.id)
                    if (result) {
                        ElMessage({
                            type: "success",
                            message: datatop.id ? '修改成功' : '添加成功'
                        });
                        arr()
                        clearForm()
                    } else {
                        ElMessage({
                            type: "error",
                            message: datatop.id ? '修改失败' : '添加失败'
                        });
                    }
                });
            } else {
                console.log('重复')
            }
        } else {
            // 表单验证失败，提示用户
            ElMessage.error('请填写正确的表单信息');
        }
    });
}
//点击删除
const delect = async (id: string) => {
    ElMessageBox.confirm('确定删除该项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 用户点击了确认按钮
        let rest: any = await remove(barID.value);
        console.log(rest);
        if (rest) {
            ElMessage({
                type: "success",
                message: '删除成功'
            });
            arr()
            clearForm()
        } else {
            ElMessage({
                type: "error",
                message: '删除失败'
            });
        }
    }).catch(() => {
        // 用户点击了取消按钮
        console.log('取消删除');
    });
}
</script>

<style scoped lang="scss">
.box {
    width: 100%;
    height: 100%;
    display: flex;

    .left_box {
        flex: 1;
        background: white;
    }

    .right_box {
        flex: 2;
        background: white;
        margin-left: 10px;
    }
}
</style>
